package com.shuimin.service.service.survey;

import com.shuimin.service.model.customer_service.*;
import pond.common.S;
import pond.db.JDBCTmpl;
import pond.db.Record;
import pond.db.sql.Criterion;
import pond.db.sql.Sql;
import pond.db.sql.SqlSelect;

import java.util.List;

/**
 * Created by sky on 2017/6/8.
 */
public class SurveyOrderService {

    public static SurveyOrder buildByTmpl(String tmpl_id, JDBCTmpl t) {

        //创建order主体
        SurveyTemp st = t.recordById(SurveyTemp.class, tmpl_id);
        if (st == null) return null;
        SurveyOrder so = (SurveyOrder) Record.newEntity(SurveyOrder.class).merge(st);
        so.setId(S.uuid.vid());


        //获取模版问答内容
        SqlSelect tmplDetailSql = Sql.select("*").from(SurveyTempDetail.class);
        tmplDetailSql.where("main_id", Criterion.EQ, st.id());
        List<SurveyTempDetail> tmplDetailList = t.query(SurveyTempDetail.class, tmplDetailSql);
        for (SurveyTempDetail item : tmplDetailList) {
            SurveyOrderDetail detail = Record.newEntity(SurveyOrderDetail.class);
            detail.merge(item);
            detail.setId(S.uuid.vid());
            detail.set("main_id", so.id());
            t.recordInsert(detail);
        }
        t.recordInsert(so);
        return so;

    }

    public static SurveyOrder getById(String id, JDBCTmpl t) {
        SurveyOrder order = t.recordById(SurveyOrder.class, id);
        if (order == null) return null;
        //获取详情
        //1.获取Q
        SqlSelect detailSql = Sql.select("*").from(VSurveyOrderDetail.class);
        detailSql.where("main_id", Criterion.EQ, id);
        detailSql.orderBy("sn asc");
        List<VSurveyOrderDetail> details = t.query(VSurveyOrderDetail.class, detailSql);
        //2.获取A
        order.put("details",S._for(details).map(item -> {
            SqlSelect aSql = Sql.select("*").from(SurveyAnswer.class);
            aSql.where("question_id", Criterion.EQ, (String)item.get("question_id"));
            aSql.orderBy("sn asc");
            List<SurveyAnswer> answer = t.query(SurveyAnswer.class, aSql);
            item.set("answers", answer);
            return item;
        }).toList());
        return order;
    }
}
